// Copyright 2007 Google, Inc. All Rights Reserved.

package com.google.jessewilson.codesearch.io;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Static utility methods for IO streams.
 * 
 * @author jessewilson
 */
public class IO {

  /**
   * Dump an input stream into bytes.
   */
  public static byte[] readFully(InputStream in) throws IOException {
    // TODO(jessewilson): optimize?
    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
    while(true) {
      int read = in.read();
      if(read == -1) break;
      out.write(read);
    }
    return out.toByteArray();
  }

  /**
   * Close the specified reader without throwing any exceptions if the close
   * fails.
   */
  public static void close(Closeable closeable) {
    try {
      if(closeable != null) {
        closeable.close();
      }
    } catch (IOException e) {
      // do nothing
    }
  }

  public static void pumpStreams(InputStream in, OutputStream out) throws IOException {
    for(int b = in.read(); b != -1; b = in.read()) {
      out.write(b);
    }
  }
}
